package com.oromwin.repos.socket.request.media;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.List;

import org.apache.commons.logging.Log;

import com.oromwin.repos.common.Common;
import com.oromwin.repos.common.Logger;
import com.oromwin.repos.common.ReposException;
import com.oromwin.repos.common.Common.ReposResult;
import com.oromwin.repos.common.Common.Status;
import com.oromwin.repos.common.helper.DBHelper;
import com.oromwin.repos.common.helper.FSHelper;
import com.oromwin.repos.common.helper.IOHelper;
import com.oromwin.repos.data.AbstractReposTable;
import com.oromwin.repos.data.MediaTable;
import com.oromwin.repos.data.VolumeTable;
import com.oromwin.repos.server.LockObject;
import com.oromwin.repos.socket.request.AbstractRequest;
import com.oromwin.repos.socket.request.RequestAction;
import com.oromwin.repos.socket.response.Response;
import com.oromwin.repos.socket.response.media.DeleteMediaResponse;

public class DeleteMediaRequest extends AbstractRequest implements RequestAction {
    private Log log = Logger.getLog(DeleteMediaRequest.class);
    private String VolumeName = null;
    private File MediaPath = null;
    private boolean _force = false;

    public DeleteMediaRequest() {
    }
    
    public DeleteMediaRequest(String volumeName, File mediaPath, boolean force) {
        VolumeName = volumeName;
        MediaPath = mediaPath;
        _force = force;
    }
    
    @Override
    public void receive(DataInputStream dis, LockObject lockObject) throws ReposException {
        try {
            VolumeName = IOHelper.readUTF8(dis);
            MediaPath = new File(IOHelper.readUTF8(dis));
            _force = dis.readBoolean();
        } catch (IOException e) {
            throw ReposException.create(log, e);
        }
    }

    @Override
    public Response run() {
        DeleteMediaResponse res = null;
        try {
            _volumeTable = (VolumeTable) getParentReposTable();
            _mediaTable = (MediaTable) getCurrentReposTable();
            checkSameObjectExists();
            String whereClause = String.format("MediaId = '%s'", _mediaTable.getMediaId());
            if (_force) {
                DBHelper.deleteTable(MediaTable.class, whereClause);
                FSHelper.delete(MediaPath);
            } else {
                _mediaTable.setMediaStatus(Status.DELETE.ordinal());
                DBHelper.updateTable(_mediaTable, whereClause);
            }
            res = new DeleteMediaResponse(ReposResult.Success, "Succeeded to delete media");
        } catch (ReposException e) {
            res = new DeleteMediaResponse(ReposResult.Failure, e.getMessage());
        }
        return res;
    }

    @Override
    public void send(DataOutputStream dos) throws ReposException {
        try {
            IOHelper.writeUTF8(dos, this.getClass().getCanonicalName());
            IOHelper.writeUTF8(dos, VolumeName);
            IOHelper.writeUTF8(dos, MediaPath.toString());
            dos.writeBoolean(_force);
            dos.flush();
        } catch (IOException e) {
            throw ReposException.create(log, e);
        }
    }

    @Override
    public void checkFreeSpaceExists() throws ReposException {
        throw ReposException.create(log, Common.Message.NOT_IMPLEMENTED_METHOD_INVOKE);
    }

    @Override
    public void checkSameObjectExists() throws ReposException {
        File filePath = MediaPath;
        if (!FSHelper.ls(filePath)) {
            String message = String.format("Same directory already exist on the server, path {%s}", filePath);
            throw ReposException.create(log, message);
        }
    }

    @Override
    public void checkDependentObjectNotExists() throws ReposException {
        String whereClause = String.format("VolumeName = '%s'", VolumeName);
        List<AbstractReposTable> list = DBHelper.selectTable(VolumeTable.class, whereClause);
        if (list.size() == 0) {
            String message = String.format("'%s' VolumeName does not exists", VolumeName);
            throw ReposException.create(log, message); 
        }
    }

    @Override
    public AbstractReposTable getCurrentReposTable() throws ReposException {
        AbstractReposTable reposTable = null;
        String whereClause = String.format("VolumeId = '%s' AND MediaStatus < 2 AND MediaPath = '%s'", _volumeTable.getVolumeId(), MediaPath);
        List<AbstractReposTable> reposTables = DBHelper.selectTable(MediaTable.class, whereClause);
        if (reposTables != null && reposTables.size() == 1) {
            reposTable = reposTables.get(0);
        } else {
            String message = String.format("MediaPath does not exists in database, VolumeName:tableSize:whereClause {%s:%d:%s}", VolumeName, reposTables.size(), whereClause);
            throw ReposException.create(log, message); 
        }
        return reposTable;
    }
    
    @Override
    public AbstractReposTable getParentReposTable() throws ReposException {
        AbstractReposTable reposTable = null;
        String whereClause = String.format("VolumeStatus < 2 AND VolumeName = '%s'", VolumeName);
        List<AbstractReposTable> reposTables = DBHelper.selectTable(VolumeTable.class, whereClause);
        if (reposTables != null && reposTables.size() == 1) {
            reposTable = reposTables.get(0);
        } else {
            String message = String.format("'%s' VolumeName does not exists in database, tableSize:whereClause {%d:%s}", VolumeName, reposTables.size(), whereClause);
            throw ReposException.create(log, message); 
        }
        return reposTable;
    }

}
